package main

import (
	"net/http"
	"github.com/julienschmidt/httprouter"
	"os"
	"time"
	"log"
	"io/ioutil"
	"io"
)

//处理视频流
func streamHandler(w http.ResponseWriter, r *http.Request,params httprouter.Params){

	vid:=params.ByName("vid-id")
	vdir:=VIDEO_DIR+vid+".mp4"

	video,err:=os.Open(vdir)
	if err!=nil{
		log.Println("处理视频流错误:"+err.Error())
		sendErrorResponse(w,http.StatusInternalServerError,"内部错误"+err.Error())
		return
	}

	w.Header().Set("Content-Type","video/mp4")
	//将文件作为二进制流返回
	log.Println(time.Now().String()+"准备返回视频流")
	http.ServeContent(w,r,"",time.Now(),video)
	log.Println(time.Now().String()+"返回视频流成功，释放文件资源")
	defer video.Close()
}

//处理视频上传
func uploadHandler(w http.ResponseWriter, r *http.Request,params httprouter.Params) {
	//限制最大上传字节
	log.Println("处理文件上传")
	r.Body=http.MaxBytesReader(w,r.Body, MAX_UPLOAD_SIZE)

	if err:=r.ParseMultipartForm(MAX_UPLOAD_SIZE);err!=nil{
		log.Println("文件过大")
		sendErrorResponse(w,http.StatusBadRequest,"文件过大")
		return
	}
	//文件上传的表单 <form name="file"
	//所以name是file
	multipartFile,_,err:=r.FormFile("video")
	if err!=nil{
		log.Println("获取文件内部错误"+err.Error())
		sendErrorResponse(w,http.StatusInternalServerError,"内部错误")
		return
	}

	data,err:=ioutil.ReadAll(multipartFile)
	if err!=nil{
		log.Println("读取文件内部错误"+err.Error())
		sendErrorResponse(w,http.StatusInternalServerError,"内部错误")
		return
	}
	log.Println("保存文件")
	fileName:=params.ByName("vid-id")
	err=ioutil.WriteFile(VIDEO_DIR+fileName+".mp4",data,0666)

	if err!=nil{
		log.Println("保存文件内部错误:"+err.Error())
		sendErrorResponse(w,http.StatusInternalServerError,"内部错误")
		return
	}

	w.WriteHeader(http.StatusCreated)
	io.WriteString(w,"上传成功")

}


//处理视频上传
func uploadHandler2(w http.ResponseWriter, r *http.Request,params httprouter.Params) {
	//限制最大上传字节
	log.Println("处理文件上传")
	r.Body=http.MaxBytesReader(w,r.Body, MAX_UPLOAD_SIZE)

	if err:=r.ParseMultipartForm(MAX_UPLOAD_SIZE);err!=nil{
		log.Println("文件过大")
		sendErrorResponse(w,http.StatusBadRequest,"文件过大")
		return
	}
	//文件上传的表单 <form name="file"
	//所以name是file
	multipartFile,_,err:=r.FormFile("video")
	if err!=nil{
		log.Println("获取文件内部错误"+err.Error())
		sendErrorResponse(w,http.StatusInternalServerError,"内部错误")
		return
	}

	data,err:=ioutil.ReadAll(multipartFile)
	if err!=nil{
		log.Println("读取文件内部错误"+err.Error())
		sendErrorResponse(w,http.StatusInternalServerError,"内部错误")
		return
	}
	log.Println("保存文件")
	fileName:=r.Form.Get("video_name")
	log.Println("文件名:"+fileName)
	err=ioutil.WriteFile(VIDEO_DIR+fileName+".mp4",data,0666)

	if err!=nil{
		log.Println("保存文件内部错误:"+err.Error())
		sendErrorResponse(w,http.StatusInternalServerError,"内部错误")
		return
	}

	w.WriteHeader(http.StatusCreated)
	io.WriteString(w,"上传成功")

}

